#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk
import re
import pango
import locale
from gettext import gettext as _

markupRe    	= re.compile( '(<u>|</u>|<i>|</i>|<b>|</b>)')
underlineRe 	= re.compile( '(<u>|</u>)')

DAY = _("day")
DAYS = _("days")
HOUR = _("h")
MINUTE = _("m")

if(locale.nl_langinfo(locale.D_FMT)[0:2] != '%d'):
	ANOTHER_DAY_FMT = "%b. %d"
else:
	ANOTHER_DAY_FMT = "%d. %b."

PointerCursor = gtk.gdk.Cursor(gtk.gdk.HAND2)

def getDateLong(d):
	return d.strftime( "%%a, %s" % ANOTHER_DAY_FMT)
class EventWidget (gtk.VBox):
	"""
	Borderless window aligning itself to a status Icon
	"""
	row_string_template = '<span %s>%s</span>' #color="%s"
	row_string_template_now = '<b>%s</b>' % row_string_template
	
	def __init__(self, event):
		gtk.VBox.__init__(self)

		name = gtk.Label()
		time_info = gtk.Label()

		name.set_alignment(0,0.5)
		name.set_ellipsize(pango.ELLIPSIZE_END)
		#name.set_padding(2,2)
		
		time_label = gtk.Label()
		time_info.set_alignment(1,0.5)

		nameEvtBox_inner = gtk.HBox()
		nameEvtBox_inner.set_border_width(4)
		nameEvtBox_inner.set_spacing(4)
		nameEvtBox_inner.pack_start(time_label,False,False)
		nameEvtBox_inner.pack_start(name,True,True)
		nameEvtBox_inner.pack_start(time_info,False,False)

		nameEvtBox = gtk.EventBox()

		nameEvtBox.add(nameEvtBox_inner)
		
		hbox1 = gtk.HBox()
		vbox1 = gtk.VBox()
		
		details = gtk.HBox()
		details.set_data('visibility',False)
		
		details_box = gtk.VBox()

		details.pack_start(gtk.Label(),False,False,10)
		details.pack_start(details_box)
		
		#print event
		markup = ""

		time_string = ''
		
		is_all_day = False
		self.color = gtk.gdk.color_parse(event.color)
		color = self.color
		if(event.is_past()):
			markup+= 'strikethrough="true"'
		if(not event.is_confirmed()):
			markup+= 'font-style="italic"'
		if(event.is_all_day()):
			is_all_day = True
			rowString = self.row_string_template % (markup, event.title )
			#time_label.set_markup('<span color="white">00:00</span>')
		else:
			#█▇▆▅▄▃▂▁■▣▪▬
			time_label.set_markup('<small><b>%s</b></small>'   % (self.getHourMinuteMarkup(event.start_time) ))
		time_info.set_markup('<small>%s</small>'  % (self.getDurationMarkup(event.duration)))		
		time_info.modify_fg(time_info.state, self.color)
		if(event.is_now()):
			rowString = self.row_string_template_now % (markup, event.title )
		else:
			rowString = self.row_string_template % (markup, event.title )
		dtext = []
		dtext.append("%s" % (event.title))


		if(is_all_day):
			if(event.duration.days >= 1):
				dtext.append("<small>%s</small>" % _("<i>until %s (%s)</i>") % (getDateLong(event.end_time),self.getDurationMarkup(event.duration)))
		else:
			dtext.append("<small><i>%s - %s (%s)</i></small>" % (self.getHourMinuteMarkup(event.start_time), self.getHourMinuteMarkup(event.end_time),self.getDurationMarkup(event.duration)))
		
		if(event.place):
			dtext.append("<b>Place:</b> %s" %(event.place))
			pass
		if(event.comment):
			dtext.append("<i>%s</i>" %(event.comment)) 
			pass

		dtext.append(_("in <i><b>%s</b></i>") % (event.cal_name))


		
		l = gtk.Label()
		l.set_alignment(0,0.5)
		l.set_selectable(True)
		l.set_line_wrap_mode(pango.WRAP_WORD_CHAR)
		l.set_line_wrap(True)

		l.set_markup("\n".join(dtext[1:]))
		details_box.pack_start(l)
		#details_box.connect("expose-event",self.details_box_exposed)
		details_box.connect("size-allocate",self.details_box_size_allocate)
		
		tooltiptext = "\n  ".join(dtext)
		
		name.set_markup('%s' % rowString)

		
		nameEvtBox.modify_bg(nameEvtBox.state,self.color)	
		nameEvtBox.set_visible_window(False)
		name.modify_fg(name.state,self.color)
		
		self.pack_start(nameEvtBox)
		self.pack_start(details)
		details.set_border_width(2)
		#self.pack_start(hbox1,True,True,2)
		#hbox1.pack_start(vbox1,True,True,50)
		#vbox1.pack_start(details)

		self.show_all()
		nameEvtBox.show()
		
		nameEvtBox.set_visible_window(False)
		nameEvtBox.connect('button-press-event',self.on_click_cb)
		nameEvtBox.connect('enter-notify-event',self.on_enter_cb,not event.is_today())
		nameEvtBox.connect('leave-notify-event',self.on_leave_cb,not event.is_today())

		details.hide()
		if(not event.is_today()):
			time_info.hide()
	
		try:
			nameEvtBox.set_tooltip_markup(tooltiptext)
		except:
			pass
		
		self.name_label = name
		self.details = details
		self.time_info = time_info
		self.time_label = time_label
		self.nameEvtBox = nameEvtBox
		
		self.setCalColor(self.time_label)
	def getDurationMarkup(self,td):
		mpart=""
		hpart=""
		dpart=""
		hours,minutes =  map(int,td.__str__()[-7:-3].split(':'))
		if(hours != 0):
			hpart = "%d%s" % (hours,HOUR)
			if(minutes != 0):
				mpart = "%d%s" % (minutes,MINUTE)		
		else:
			if(minutes != 0):
				mpart = "%d%s" % (minutes,MINUTE)
		if(td.days != 0):
			if(td.days == 1):
				dpart = "%d%s " % (td.days,DAY)
			else:
				dpart = "%d%s " % (td.days,DAYS)
		return ("%s%s%s" %(dpart,hpart,mpart)).strip()
		
	def getHourMinuteMarkup(self,dt):
		return dt.strftime(TIME_FMT)
	def getHourMinuteMarkup_ampm(self,dt):
		return dt.strftime(TIME_FMT).replace(':00','').strip()
	def on_enter_cb(self,widget,event,toggle_timeinfo = True):
		
		if(toggle_timeinfo):
			self.time_info.show()
		t = underlineRe.sub('',self.name_label.get_label())
		self.name_label.set_markup("<u>%s</u>" % t)

		self.nameEvtBox.window.set_cursor(PointerCursor)
	
	def on_leave_cb(self,widget,event,toggle_timeinfo = True):
		
		if(toggle_timeinfo):
			self.time_info.hide()
		t = underlineRe.sub('',self.name_label.get_label())
		self.name_label.set_markup(t)

		self.nameEvtBox.window.set_cursor(None)

		pass
	def on_click_cb(self, widget,event):
		#print "on_click_cb"
		if (event.button == 1):
			
			try:
				if(self.details.get_property('visible')):
					self.details.hide()
				else:
					self.details.show()
			except:
				pass
		return False
	def setCalColor(self,widget):
		widget.modify_fg(widget.state,self.color)
	def setWhiteColor(self,widget):
		widget.modify_fg(widget.state,widget.style.white)
	def details_box_size_allocate(self,widget,rect):
		#print rect.width
		w = rect.width - 10
		for l in widget.get_children():
			l.set_size_request(w,-1)
		pass
	

if(locale.nl_langinfo(locale.T_FMT_AMPM) != ''):
	TIME_FMT = locale.nl_langinfo(locale.T_FMT_AMPM).replace(':%S ','')
	EventWidget.getHourMinuteMarkup = EventWidget.getHourMinuteMarkup_ampm
else:
	TIME_FMT = "%H:%M"
